<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>检验任务</span>
        </div>
      </template>
      
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
        <el-form-item label="任务编号" prop="taskCode">
          <el-input
            v-model="queryParams.taskCode"
            placeholder="请输入任务编号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input
            v-model="queryParams.productName"
            placeholder="请输入产品名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="任务状态" prop="taskStatus">
          <el-select v-model="queryParams.taskStatus" placeholder="请选择任务状态" clearable>
            <el-option
              v-for="dict in taskStatusOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="计划日期">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['qep:inspection:task:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['qep:inspection:task:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['qep:inspection:task:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['qep:inspection:task:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="任务编号" align="center" prop="taskCode" />
        <el-table-column label="产品名称" align="center" prop="productName" :show-overflow-tooltip="true" />
        <el-table-column label="批次号" align="center" prop="batchCode" />
        <el-table-column label="工序名称" align="center" prop="processName" :show-overflow-tooltip="true" />
        <el-table-column label="检验类型" align="center" prop="inspectionType" />
        <el-table-column label="计划日期" align="center" prop="planDate" width="100">
          <template #default="scope">
            <span>{{ parseTime(scope.row.planDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="检验人员" align="center" prop="inspector" />
        <el-table-column label="任务状态" align="center" prop="taskStatus">
          <template #default="scope">
            <el-tag :type="getTaskStatusType(scope.row.taskStatus)">
              {{ getTaskStatusText(scope.row.taskStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button 
              link type="primary" 
              icon="View" 
              @click="handleView(scope.row)"
              v-hasPermi="['qep:inspection:task:query']"
            >查看</el-button>
            <el-button 
              link type="primary" 
              icon="Edit" 
              @click="handleUpdate(scope.row)" 
              v-hasPermi="['qep:inspection:task:edit']"
              v-if="scope.row.taskStatus === 1"
            >修改</el-button>
            <el-button 
              link type="primary" 
              icon="User" 
              @click="handleAssign(scope.row)" 
              v-hasPermi="['qep:inspection:task:assign']"
              v-if="scope.row.taskStatus === 1"
            >分配</el-button>
            <el-button 
              link type="primary" 
              icon="VideoPlay" 
              @click="handleStart(scope.row)" 
              v-hasPermi="['qep:inspection:task:start']"
              v-if="scope.row.taskStatus === 1 && scope.row.inspector"
            >开始</el-button>
            <el-button 
              link type="primary" 
              icon="Check" 
              @click="handleFinish(scope.row)" 
              v-hasPermi="['qep:inspection:task:finish']"
              v-if="scope.row.taskStatus === 2"
            >完成</el-button>
            <el-button 
              link type="primary" 
              icon="Document" 
              @click="handleData(scope.row)" 
              v-hasPermi="['qep:inspection:data:list']"
              v-if="scope.row.taskStatus === 2 || scope.row.taskStatus === 3"
            >数据</el-button>
            <el-button 
              link type="primary" 
              icon="Delete" 
              @click="handleDelete(scope.row)" 
              v-hasPermi="['qep:inspection:task:remove']"
              v-if="scope.row.taskStatus === 1"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改检验任务对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="taskFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="任务编号" prop="taskCode">
              <el-input v-model="form.taskCode" placeholder="自动生成" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品" prop="productId">
              <el-select v-model="form.productId" placeholder="请选择产品" @change="handleProductChange">
                <el-option
                  v-for="item in productOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="批次" prop="batchId">
              <el-select v-model="form.batchId" placeholder="请选择批次" @change="handleBatchChange">
                <el-option
                  v-for="item in batchOptions"
                  :key="item.id"
                  :label="item.batchCode"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工序" prop="processId">
              <el-select v-model="form.processId" placeholder="请选择工序">
                <el-option
                  v-for="item in processOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="检验类型" prop="inspectionType">
              <el-input v-model="form.inspectionType" placeholder="请输入检验类型" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划日期" prop="planDate">
              <el-date-picker
                v-model="form.planDate"
                type="date"
                placeholder="选择日期"
                value-format="YYYY-MM-DD"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="抽样数量" prop="sampleQuantity">
              <el-input-number v-model="form.sampleQuantity" :min="1" :max="1000" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="form.priority" placeholder="请选择优先级">
                <el-option label="低" value="1" />
                <el-option label="中" value="2" />
                <el-option label="高" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配检验任务对话框 -->
    <el-dialog title="分配检验任务" v-model="assignOpen" width="550px" append-to-body>
      <el-form ref="assignFormRef" :model="assignForm" :rules="assignRules" label-width="80px">
        <el-form-item label="检验人员" prop="inspector">
          <el-select v-model="assignForm.inspector" placeholder="请选择检验人员" filterable>
            <template #empty>
              <el-empty description="未找到检验人员">
                <span style="font-size: 12px; color: #909399; margin-top: 10px; display: block;">
                  请先在系统中创建"检验人员"角色，并为相关用户分配该角色
                </span>
              </el-empty>
            </template>
            <el-option
              v-for="item in userOptions"
              :key="item.userId"
              :label="item.nickName"
              :value="item.nickName"
            >
              <span>{{ item.nickName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.deptName }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-alert
          v-if="userOptions.length === 0"
          title="提示：只有拥有'检验人员'角色的用户才能被选为检验人员"
          type="info"
          description="可在'系统管理-角色管理'中创建检验人员角色并分配给用户"
          show-icon
          :closable="false"
          style="margin-top: 10px"
        />
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAssignForm">确 定</el-button>
          <el-button @click="cancelAssign">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 完成检验任务对话框 -->
    <el-dialog title="完成检验任务" v-model="finishOpen" width="500px" append-to-body>
      <el-form ref="finishFormRef" :model="finishForm" :rules="finishRules" label-width="100px">
        <el-form-item label="实际日期" prop="actualDate">
          <el-date-picker
            v-model="finishForm.actualDate"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="检验结论" prop="inspectionResult">
          <el-select v-model="finishForm.inspectionResult" placeholder="请选择检验结论">
            <el-option label="合格" value="合格" />
            <el-option label="不合格" value="不合格" />
            <el-option label="特采" value="特采" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFinishForm">确 定</el-button>
          <el-button @click="cancelFinish">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import { parseTime } from '@/utils/ruoyi';
import { download } from '@/utils/request';
import { addDateRange } from '@/utils/ruoyi';
import { 
  listInspectionTask, 
  getInspectionTask, 
  addInspectionTask, 
  updateInspectionTask, 
  delInspectionTask, 
  assignInspectionTask,
  startInspectionTask,
  finishInspectionTask,
  generateTaskCode
} from '@/api/qep/inspection/task';
import { listProduct } from '@/api/qep/product';
import { listBatch } from '@/api/qep/production/batch';
import { listProcess } from '@/api/qep/process';
import { listUser } from '@/api/system/user';
import { allocatedUserList, listRole } from '@/api/system/role';

const router = useRouter();

// 遮罩层
const loading = ref(false);
// 选中数组
const ids = ref([]);
// 非单个禁用
const single = computed(() => ids.value.length !== 1);
// 非多个禁用
const multiple = computed(() => ids.value.length === 0);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 检验任务表格数据
const taskList = ref([]);
// 弹出层标题
const title = ref("");
// 是否显示弹出层
const open = ref(false);
// 是否显示分配弹出层
const assignOpen = ref(false);
// 是否显示完成弹出层
const finishOpen = ref(false);
// 日期范围
const dateRange = ref([]);
// 产品下拉选项
const productOptions = ref([]);
// 批次下拉选项
const batchOptions = ref([]);
// 工序下拉选项
const processOptions = ref([]);
// 任务状态下拉选项
const taskStatusOptions = ref([
  { value: 1, label: '待检验' },
  { value: 2, label: '检验中' },
  { value: 3, label: '已完成' }
]);
// 用户下拉选项
const userOptions = ref([]);
// 检验人员角色ID（默认设置一个初始值，会动态查询）
const inspectorRoleId = ref(null);

// 表单引用
const taskFormRef = ref(null);
const assignFormRef = ref(null);
const finishFormRef = ref(null);

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  taskCode: undefined,
  productName: undefined,
  taskStatus: undefined
});

// 表单参数
const form = reactive({
  id: undefined,
  taskCode: undefined,
  productId: undefined,
  batchId: undefined,
  processId: undefined,
  inspectionType: undefined,
  planDate: undefined,
  sampleQuantity: 1,
  priority: '2',
  remark: undefined
});

// 分配表单参数
const assignForm = reactive({
  id: undefined,
  inspector: undefined
});

// 完成表单参数
const finishForm = reactive({
  id: undefined,
  actualDate: undefined,
  inspectionResult: '合格'
});

// 表单校验
const rules = reactive({
  productId: [
    { required: true, message: "请选择产品", trigger: "change" },
    { validator: validateProduct, trigger: "change" }
  ],
  batchId: [
    { required: true, message: "请选择批次", trigger: "change" },
    { validator: validateBatch, trigger: "change" }
  ],
  processId: [
    { required: true, message: "请选择工序", trigger: "change" },
    { validator: validateProcess, trigger: "change" }
  ],
  inspectionType: [
    { required: true, message: "请输入检验类型", trigger: "blur" },
    { min: 2, max: 50, message: "检验类型长度在2到50个字符", trigger: "blur" },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z0-9\s]+$/, message: "检验类型只能包含中文、英文、数字和空格", trigger: "blur" }
  ],
  planDate: [
    { required: true, message: "请选择计划日期", trigger: "change" },
    { validator: validatePlanDate, trigger: "change" }
  ],
  sampleQuantity: [
    { required: true, message: "请输入抽样数量", trigger: "blur" },
    { type: 'number', min: 1, max: 10000, message: "抽样数量应在1到10000之间", trigger: "blur" },
    { validator: validateSampleQuantity, trigger: "blur" }
  ],
  priority: [
    { required: true, message: "请选择优先级", trigger: "change" }
  ],
  remark: [
    { max: 500, message: "备注长度不能超过500个字符", trigger: "blur" }
  ]
});

// 分配表单校验
const assignRules = reactive({
  inspector: [
    { required: true, message: "请选择检验人员", trigger: "change" },
    { validator: validateInspector, trigger: "change" }
  ]
});

// 完成表单校验
const finishRules = reactive({
  actualDate: [
    { required: true, message: "请选择实际日期", trigger: "change" },
    { validator: validateActualDate, trigger: "change" }
  ],
  inspectionResult: [
    { required: true, message: "请选择检验结论", trigger: "change" }
  ]
});

// 自定义验证器

// 验证产品选择
function validateProduct(rule, value, callback) {
  if (!value) {
    callback(new Error('请选择产品'));
    return;
  }
  
  // 检查产品是否存在
  const product = productOptions.value.find(item => item.id === value);
  if (!product) {
    callback(new Error('选择的产品不存在，请重新选择'));
    return;
  }
  
  // 检查产品状态
  if (product.status === '0') {
    callback(new Error('选择的产品已停用，无法创建检验任务'));
    return;
  }
  
  callback();
}

// 验证批次选择
function validateBatch(rule, value, callback) {
  if (!value) {
    callback(new Error('请选择批次'));
    return;
  }
  
  // 检查批次是否存在
  const batch = batchOptions.value.find(item => item.id === value);
  if (!batch) {
    callback(new Error('选择的批次不存在，请重新选择'));
    return;
  }
  
  // 检查批次状态
  if (batch.status === '已完成') {
    callback(new Error('选择的批次已完成，无法创建检验任务'));
    return;
  }
  
  // 检查批次与产品的关联
  if (form.productId && batch.productId !== form.productId) {
    callback(new Error('选择的批次与产品不匹配，请重新选择'));
    return;
  }
  
  callback();
}

// 验证工序选择
function validateProcess(rule, value, callback) {
  if (!value) {
    callback(new Error('请选择工序'));
    return;
  }
  
  // 检查工序是否存在
  const process = processOptions.value.find(item => item.id === value);
  if (!process) {
    callback(new Error('选择的工序不存在，请重新选择'));
    return;
  }
  
  // 检查工序状态
  if (process.status === '0') {
    callback(new Error('选择的工序已停用，无法创建检验任务'));
    return;
  }
  
  callback();
}

// 验证计划日期
function validatePlanDate(rule, value, callback) {
  if (!value) {
    callback(new Error('请选择计划日期'));
    return;
  }
  
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const planDate = new Date(value);
  
  // 检查日期不能是过去的日期
  if (planDate < today) {
    callback(new Error('计划日期不能早于今天'));
    return;
  }
  
  // 检查日期不能超过3个月后
  const maxDate = new Date(today);
  maxDate.setMonth(maxDate.getMonth() + 3);
  if (planDate > maxDate) {
    callback(new Error('计划日期不能超过3个月'));
    return;
  }
  
  callback();
}

// 验证抽样数量
function validateSampleQuantity(rule, value, callback) {
  if (!value && value !== 0) {
    callback(new Error('请输入抽样数量'));
    return;
  }
  
  if (!Number.isInteger(value) || value < 1) {
    callback(new Error('抽样数量必须是大于0的整数'));
    return;
  }
  
  // 如果已选择批次，检查抽样数量不能超过批次数量
  if (form.batchId) {
    const batch = batchOptions.value.find(item => item.id === form.batchId);
    if (batch && batch.quantity && value > batch.quantity) {
      callback(new Error(`抽样数量不能超过批次数量(${batch.quantity})`));
      return;
    }
  }
  
  callback();
}

// 验证检验人员
function validateInspector(rule, value, callback) {
  if (!value) {
    callback(new Error('请选择检验人员'));
    return;
  }
  
  // 检查检验人员是否存在
  const inspector = userOptions.value.find(item => item.nickName === value);
  if (!inspector) {
    callback(new Error('选择的检验人员不存在，请重新选择'));
    return;
  }
  
  // 检查检验人员状态
  if (inspector.status === '1') {
    callback(new Error('选择的检验人员已停用，无法分配任务'));
    return;
  }
  
  callback();
}

// 验证实际日期
function validateActualDate(rule, value, callback) {
  if (!value) {
    callback(new Error('请选择实际日期'));
    return;
  }
  
  const actualDate = new Date(value);
  const today = new Date();
  today.setHours(23, 59, 59, 999);
  
  // 检查实际日期不能是未来的日期
  if (actualDate > today) {
    callback(new Error('实际日期不能是未来的日期'));
    return;
  }
  
  // 如果有计划日期，检查实际日期与计划日期的差异
  if (finishForm.planDate) {
    const planDate = new Date(finishForm.planDate);
    const diffDays = Math.ceil((actualDate - planDate) / (1000 * 60 * 60 * 24));
    
    if (diffDays < -7) {
      callback(new Error('实际日期比计划日期提前超过7天，请确认'));
      return;
    }
    
    if (diffDays > 30) {
      callback(new Error('实际日期比计划日期延后超过30天，请确认'));
      return;
    }
  }
  
  callback();
}

// 实时验证辅助函数

// 产品变更时的处理
function handleProductChange(productId) {
  // 清空依赖字段
  form.batchId = undefined;
  form.processId = undefined;
  
  // 重新验证表单
  nextTick(() => {
    if (taskFormRef.value) {
      taskFormRef.value.clearValidate(['batchId', 'processId']);
    }
  });
  
  // 根据产品ID筛选批次和工序
  if (productId) {
    // 筛选对应产品的批次
    getBatchByProductId(productId);
    // 筛选对应产品的工序
    getProcessByProductId(productId);
  } else {
    batchOptions.value = [];
    processOptions.value = [];
  }
}

// 根据产品ID获取批次
function getBatchByProductId(productId) {
  listBatch({ productId }).then(response => {
    batchOptions.value = response.rows || [];
  }).catch(error => {
    console.error('获取批次列表失败:', error);
    batchOptions.value = [];
  });
}

// 根据产品ID获取工序
function getProcessByProductId(productId) {
  listProcess({ productId }).then(response => {
    processOptions.value = response.rows || [];
  }).catch(error => {
    console.error('获取工序列表失败:', error);
    processOptions.value = [];
  });
}

// 批次变更时的处理
function handleBatchChange(batchId) {
  // 重新验证抽样数量
  nextTick(() => {
    if (taskFormRef.value) {
      taskFormRef.value.validateField('sampleQuantity');
    }
  });
}

// 业务规则验证
function validateBusinessRules() {
  // 检查同一产品批次工序是否已存在检验任务
  const existingTask = taskList.value.find(task => 
    task.productId === form.productId && 
    task.batchId === form.batchId && 
    task.processId === form.processId &&
    task.id !== form.id &&
    task.taskStatus !== 3 // 不是已完成状态
  );
  
  if (existingTask) {
    ElMessage.warning('该产品批次工序已存在进行中的检验任务，请先完成或取消现有任务');
    return false;
  }
  
  // 检查计划日期是否与现有任务冲突（同一检验人员同一天的任务数量限制）
  if (form.inspector && form.planDate) {
    const sameDayTasks = taskList.value.filter(task => 
      task.inspector === form.inspector && 
      task.planDate === form.planDate &&
      task.id !== form.id &&
      task.taskStatus !== 3
    );
    
    if (sameDayTasks.length >= 5) {
      ElMessage.warning('该检验人员在此日期已有5个任务，建议调整计划日期或分配给其他人员');
      return false;
    }
  }
  
  return true;
}

// 获取任务状态样式
function getTaskStatusType(status) {
  switch (status) {
    case 1: return '';
    case 2: return 'warning';
    case 3: return 'success';
    default: return 'info';
  }
}

// 获取任务状态文本
function getTaskStatusText(status) {
  const option = taskStatusOptions.value.find(item => item.value === status);
  return option ? option.label : '未知';
}

/** 查询检验任务列表 */
function getList() {
  loading.value = true;
  listInspectionTask(addDateRange(queryParams, dateRange.value)).then(response => {
    taskList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 查询产品列表 */
function getProductList() {
  listProduct().then(response => {
    productOptions.value = response.rows;
  });
}

/** 查询批次列表 */
function getBatchList() {
  listBatch().then(response => {
    batchOptions.value = response.rows;
  });
}

/** 查询工序列表 */
function getProcessList() {
  listProcess().then(response => {
    processOptions.value = response.rows;
  });
}

/** 查询用户列表 */
function getUserList() {
  console.log('开始获取检验人员列表');
  
  // 直接从质检部门获取用户
  listUser({ deptId: 4, status: 0 }).then(response => {
    userOptions.value = response.rows;
    console.log('成功获取质检部门用户列表:', userOptions.value.length, '条记录');
    
    if (userOptions.value.length === 0) {
      // 如果质检部门没有人员，获取所有具有检验人员角色的用户
      allocatedUserList({ roleId: 100 }).then(roleResponse => {
        userOptions.value = roleResponse.rows;
        console.log('通过角色ID获取用户列表:', userOptions.value.length, '条记录');
      });
    }
  }).catch(error => {
    console.error('获取用户列表失败:', error);
    ElMessage.error('获取检验人员列表失败');
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  resetForm();
}

/** 取消分配按钮 */
function cancelAssign() {
  assignOpen.value = false;
  resetAssignForm();
}

/** 取消完成按钮 */
function cancelFinish() {
  finishOpen.value = false;
  resetFinishForm();
}

/** 表单重置 */
function resetForm() {
  form.id = undefined;
  form.taskCode = undefined;
  form.productId = undefined;
  form.batchId = undefined;
  form.processId = undefined;
  form.inspectionType = undefined;
  form.planDate = undefined;
  form.sampleQuantity = 1;
  form.priority = '2';
  form.remark = undefined;
  
  // 重置表单验证状态
  if (taskFormRef.value) {
    taskFormRef.value.resetFields();
  }
}

/** 分配表单重置 */
function resetAssignForm() {
  assignForm.id = undefined;
  assignForm.inspector = undefined;
  
  // 重置表单验证状态
  if (assignFormRef.value) {
    assignFormRef.value.resetFields();
  }
}

/** 完成表单重置 */
function resetFinishForm() {
  finishForm.id = undefined;
  finishForm.actualDate = undefined;
  finishForm.inspectionResult = '合格';
  
  // 重置表单验证状态
  if (finishFormRef.value) {
    finishFormRef.value.resetFields();
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    taskCode: undefined,
    productName: undefined,
    taskStatus: undefined
  });
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
}

/** 新增按钮操作 */
function handleAdd() {
  resetForm();
  open.value = true;
  title.value = "添加检验任务";
  
  // 获取任务编号
  generateTaskCode().then(response => {
    form.taskCode = response.data;
  });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  resetForm();
  const taskId = row.id || ids.value[0];
  getInspectionTask(taskId).then(response => {
    Object.assign(form, response.data);
    open.value = true;
    title.value = "修改检验任务";
  });
}

/** 提交按钮 */
function submitForm() {
  if (!taskFormRef.value) return;
  
  taskFormRef.value.validate(valid => {
    if (valid) {
      // 额外的业务逻辑验证
      if (!validateBusinessRules()) {
        return;
      }
      
      if (form.id) {
    updateInspectionTask(form).then(response => {
          ElMessage.success("修改成功");
      open.value = false;
      getList();
        }).catch(error => {
          ElMessage.error("修改失败：" + (error.message || '未知错误'));
    });
  } else {
    addInspectionTask(form).then(response => {
          ElMessage.success("新增成功");
      open.value = false;
      getList();
        }).catch(error => {
          ElMessage.error("新增失败：" + (error.message || '未知错误'));
    });
  }
    } else {
      ElMessage.warning("请检查表单填写是否正确");
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const taskIds = row.id || ids.value;
  ElMessageBox.confirm(
    '确认删除选中的检验任务?',
    "警告",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(function() {
    return delInspectionTask(taskIds);
  }).then(() => {
    getList();
    ElMessage({
      message: '删除成功',
      type: 'success',
    });
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  download('/qep/inspection/task/export', {
    ...queryParams,
    ...addDateRange(queryParams, dateRange)
  }, `inspection_task_${new Date().getTime()}.xlsx`);
}

/** 查看详情按钮操作 */
function handleView(row) {
  router.push(`/inspection/task/detail/${row.id}`);
}

/** 分配按钮操作 */
function handleAssign(row) {
  resetAssignForm();
  assignForm.id = row.id;
  assignOpen.value = true;
  console.log('打开分配对话框, 任务ID:', row.id);
  
  // 立即获取检验人员列表
  getUserList();
}

/** 提交分配表单 */
function submitAssignForm() {
  console.log('准备分配表单, 当前表单数据:', JSON.stringify(assignForm));
  
  // 表单值检查
  if (!assignForm.id) {
    console.error('任务ID为空');
    ElMessage.error('提交失败：任务ID为空');
    return;
  }
  
  if (!assignForm.inspector) {
    console.error('检验人员为空');
    ElMessage.warning('请选择检验人员');
    return;
  }
  
  // 打印完整的提交对象
  const submitData = {
    id: assignForm.id,
    inspector: assignForm.inspector
  };
  console.log('最终提交数据:', JSON.stringify(submitData));
  
  // 提交请求
  assignInspectionTask(submitData)
    .then(response => {
      console.log('分配成功，响应:', response);
      ElMessage.success('分配成功');
      assignOpen.value = false;
      getList();
    })
    .catch(error => {
      console.error('分配失败:', error);
      ElMessage.error('分配失败：' + (error.message || '未知错误'));
    });
}

/** 开始任务按钮操作 */
function handleStart(row) {
  ElMessageBox.confirm(
    '确认开始任务"' + row.taskCode + '"?',
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "info",
    }
  ).then(function() {
    return startInspectionTask(row.id);
  }).then(() => {
    getList();
    ElMessage({
      message: '任务已开始',
      type: 'success',
    });
  }).catch(() => {});
}

/** 完成任务按钮操作 */
function handleFinish(row) {
  resetFinishForm();
  finishForm.id = row.id;
  finishOpen.value = true;
}

/** 提交完成表单 */
function submitFinishForm() {
  if (!finishForm.actualDate) {
    ElMessage({
      message: '请选择实际完成日期',
      type: 'warning',
    });
    return;
  }
  
  finishInspectionTask(finishForm).then(response => {
    ElMessage({
      message: '任务已完成',
      type: 'success',
    });
    finishOpen.value = false;
    getList();
  });
}

/** 查看数据按钮操作 */
function handleData(row) {
  router.push(`/inspection/data/task/${row.id}`);
}

onMounted(() => {
  getList();
  getProductList();
  getBatchList();
  getProcessList();
  getUserList();
});
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 